<?php

namespace Frieza\Modules\Lottery\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Lottery\LotteryActivity;
use Doraemon\model\Lottery\LotteryActivitySeries;
use Doraemon\model\Lottery\LotteryAwardUser;
use Doraemon\model\Lottery\LotteryPrize;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class SeriesController extends Controller
{

    const PAGE_SIZE = 20;


    public function index(Request $request, Content $content, $activity_id)
    {
        $where = [
            "AND" => [
                "activity_id" => $activity_id,
                "a_status" => LotteryActivitySeries::STATUS_NORMAL,
            ],
            'ORDER' => [
                'id' => 'DESC'
            ]
        ];

        $result = [];
        $result['list'] = LotteryActivitySeries::selectByWhere($where);

        unset($where['ORDER']);
        unset($where['LIMIT']);
        $result['total'] = LotteryActivitySeries::selectCount($where);
        $grid = new pGridDataModel($result['list'], $result['total']);
        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->column('id');
                $grid->column('activity_id', '抽奖活动id');
                $grid->column('activity_number', '期数');
                $grid->column('start_time', '开始时间');
                $grid->column('end_time', '结束时间');
                $grid->column('open_time', '开奖时间');
                $grid->column('max_lottery_times', '最大可抽奖次数');
                $grid->column('prize_index', '奖品列表')->display(function () {
                    $html = '<a href="' . url('/admin/lottery/series/' . $this->id . '/prize/index') . '">奖品列表</a>';
                    return $html;
                })->width(100);
                $grid->column('awarduser_index', '中奖用户')->display(function () {
                    $html = '<a href="' . url('/admin/lottery/series/' . $this->id . '/awarduser/index') . '">中奖用户</a>';
                    return $html;
                })->width(100);
                $grid->column('addtime', '添加时间');
                $grid->column('edittime', '修改时间');
                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
            });

        $content->row($gridList);
        return $content
            ->header('期数列表')
            ->description(' ')
            ->breadcrumb(['text' => 'lottery']);
    }

    //新建/编辑页面
    public function edit(Content $content, $activity_id = 0, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑抽奖活动期数';
        } else {
            $title = '创建抽奖活动期数';
        }
        $tab->add("$title", $this->editAction($activity_id, $id));
        return $content
            ->header('期数管理')
            ->breadcrumb(
                [
                    'text' => '期数列表',
                    'url' => '/activity/' . $id . '/series/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($activity_id, $id = 0)
    {
        $common_data = ['activity_id' => $activity_id];
        if ($id > 0) {
            $data = LotteryActivitySeries::getById($id);
            $form = new Form(array_merge($data, $common_data));
            $form->hidden('id');
        } else {
            $form = new Form($common_data);
        }
        $form->hidden('activity_id');
        $form->number('activity_number', '期数')->required();
        $form->datetime('start_time', '开始时间')->required();
        $form->datetime('end_time', '结束时间')->required();
        $form->radio('open_type', '开奖方式')->options([1 => '立即开奖', 2 => '定时开奖'])->default(1);
        $form->number('max_lottery_times', '最大可抽奖次数')->required();
        $form->action('/admin/lottery/activity/series/index/save');
        return $form;
    }

    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        $data = [
            'activity_id' => $params['activity_id'],
            'activity_number' => $params['activity_number'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
            'open_type' => $params['open_type'],
            'max_lottery_times' => $params['max_lottery_times'],
            'admin_id' => Admin::user()->id,
        ];
        if (isset($params['id']) && $params['id']) {
            //编辑
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = LotteryActivitySeries::editData($params['id'], $data);

        } else {
            //创建
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $data['a_status'] = LotteryActivitySeries::STATUS_NORMAL;
            $rs = LotteryActivitySeries::addData($data);
        }
        if ($rs) {
            $success = new MessageBag([
                'title' => '保存成功,可以去设置投票项啦'
            ]);
            return redirect('/admin/lottery/activity/' . $params['activity_id'] . '/series/index')->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function del(Request $request, $activity_id = 0, $id = 0)
    {
        try {
            if ($id) {
                LotteryActivitySeries::editData(['id' => $id], ['a_status' => LotteryActivitySeries::STATUS_DELETE]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);

            } else {
                throw new \Exception('不存在的id');
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json($success);
    }

    public function awardUserList(Request $request, Content $content, $series_id)
    {
        $where = [
            "AND" => [
                "activity_num_id" => $series_id,
            ],
            'ORDER' => [
                'id' => 'DESC'
            ]
        ];

        $result = [];
        $result['list'] = LotteryAwardUser::selectByWhere($where);

        $format_award_user_list = [];
        if ($result['list']){
            foreach ($result['list'] as $award_user_item){
                $activity_info = LotteryActivity::getActivityById($award_user_item['activity_id']);
                $series_info = LotteryActivitySeries::getById($award_user_item['activity_num_id']);
                $prize_info = LotteryPrize::getById($award_user_item['prize_id']);
                $user_info = User::getUser($award_user_item['uid']);

                $format_award_user_list[] = [
                    "id" => $award_user_item['id'],
                    "uid" => $award_user_item['uid'],
                    "nick" => $user_info['nick'],
                    "activity_title" => $activity_info['award_title'],
                    "award_num_title" => "第{$series_info['activity_number']}期",
                    "prize_name" => $prize_info['prize_name'],
                    "award_date" => $award_user_item['award_date'],
                    "addtime" => $award_user_item['addtime']
                ];
            }
        }

        unset($where['ORDER']);
        unset($where['LIMIT']);
        $result['total'] = LotteryAwardUser::selectCount($where);
        $grid = new pGridDataModel($format_award_user_list, $result['total']);
        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disableCreateButton();
                $grid->disableActions();

                $grid->column('id');
                $grid->column('uid', '中奖用户uid');
                $grid->column('nick', '中奖用户昵称');
                $grid->column('activity_title', '抽奖活动标题');
                $grid->column('award_num_title', '期数');
                $grid->column('prize_name', '奖品名称');
                $grid->column('award_date', '中奖日期');
                $grid->column('addtime', '添加时间');
            });

        $content->row($gridList);
        return $content
            ->header('中奖用户列表')
            ->description(' ')
            ->breadcrumb(['text' => 'lottery']);
    }
}
